package com.toro.server.handler;

import com.toro.dao.GroupSession;
import com.toro.dao.GroupSessionFactory;
import com.toro.message.GroupQuitRequestMessage;
import com.toro.message.GroupQuitResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: GroupQuitRequestMessageHandler
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/11 17:50
 */
@Slf4j
@ChannelHandler.Sharable
public class GroupQuitRequestMessageHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupQuitRequestMessage groupQuitRequestMessage) throws Exception {
        log.info("退出群请求体:{}", groupQuitRequestMessage);
        String groupName = groupQuitRequestMessage.getGroupName();
        String username = groupQuitRequestMessage.getUsername();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        boolean emptyGroup = groupSession.EmptyGroup(groupName);
        GroupQuitResponseMessage quitResponseMessage = null;
        if (emptyGroup) {
            groupSession.removeMember(groupName, username);
            quitResponseMessage = new GroupQuitResponseMessage(true, "用户：" + username + "成功移除群" + groupName);
            channelHandlerContext.writeAndFlush(quitResponseMessage);
        } else {
            quitResponseMessage = new GroupQuitResponseMessage(false, "群" + groupName + "不存在");
            channelHandlerContext.writeAndFlush(quitResponseMessage);
        }
        log.info("加入群响应体：{}", quitResponseMessage);
    }
}
